<template>
  <div :id="id"></div>
</template>

<script>
  import E from 'wangeditor'
  import uploadApi from '@/api/upload'

  export default {
    name: 'WangEditor',
    props: {
      id: {
        type: String,
        default: 'editor'
      },
      height: {
        type: Number,
        default: 500
      }
    },
    data() {
      return {
        editor: {}
      }
    },
    methods: {
      init() {
        this.editor = new E('#' + this.id)

        // 设置编辑区域高度为 500px
        this.editor.config.height = this.height

        this.editor.config.customUploadImg = function(resultFiles, insertImgFn) {
          // resultFiles 是 input 中选中的文件列表
          // insertImgFn 是获取图片 url 后，插入到编辑器的方法
          resultFiles.forEach(file => {
            let formData = new FormData()
            formData.append('file', file)
            uploadApi.upload(formData).then(res => {
              // 上传图片，返回结果，将图片插入到编辑器中
              insertImgFn(process.env.VUE_APP_BASE_IMAGE_URL + res.data.file)
            })
          })
        }

        // editor.config.customUploadVideo = function (resultFiles, insertVideoFn) {
        //   resultFiles.forEach(file => {
        //     let formData = new FormData();
        //     formData.append("file", file);
        //     uploadApi.upload(formData).then(res => {
        //       insertVideoFn(process.env.VUE_APP_BASE_IMAGE_URL + res.data.file)
        //     })
        //   })
        // }

        this.editor.create()
      },
      get() {
        return this.editor.txt.html()
      },
      set(text) {
        this.editor.txt.text(text)
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.init()
      })
    }
  }
</script>

<style scoped>

</style>
